package org.example.guice;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;

public class GuiceApplicationContext {

    private Injector injector;

    private boolean state = false;

    private final Set<Module> modules = new LinkedHashSet<>();

    public GuiceApplicationContext(Class<?>... primarySources) {
        this.modules.add(new AutoImportModule(primarySources));
    }

    public GuiceApplicationContext addModule(Module... modules) {
        Optional.of(state).filter(Boolean::booleanValue).orElseThrow(() -> new RuntimeException("container started!"));
        this.modules.addAll(Arrays.asList(modules));
        return this;
    }

    public GuiceApplicationContext run() {
        this.injector = Guice.createInjector(modules);
        this.state = true;
        return this;
    }

    public <T> T getBean(Class<T> beanClass) {
        return this.injector.getInstance(beanClass);
    }

    public static GuiceApplicationContext run(Class<?>... primarySources) {
        return new GuiceApplicationContext(primarySources).run();
    }


}
